using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Threading;
using System.Net;
using System.Drawing;

namespace DeliciousToolbar
{
    public class FaviconFetcherAsync
    {
        public List<RecentBookmark> RecentBookmarks;

        public event FaviconFetchCompletedEventHandler FaviconFetchCompleted;

        public FaviconFetcherAsync()
        {
            RecentBookmarks = null;
        }

        public void BeginFetchFavicons(List<RecentBookmark> recentBookmarks)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(FetchFavicons), recentBookmarks);
        }

        private void FetchFavicons(object recentBookmarks)
        {
            foreach (RecentBookmark Bookmark in (List<RecentBookmark>)recentBookmarks)
            {
                if (Bookmark.Favicon == null)
                {
                    WebRequest WR = WebRequest.Create(Bookmark.FaviconUri.ToString());

                    try
                    {
                        using (WebResponse Response = WR.GetResponse())
                        {
                            Bookmark.Favicon = new Bitmap(Response.GetResponseStream());
                            Bookmark.Favicon = new Bitmap(Bookmark.Favicon, new Size(15, 15));
                        }
                    }
                    catch (Exception) { }
                }
            }

            FaviconFetchCompleted(this, new FaviconFetchCompletedEventArgs((List<RecentBookmark>)recentBookmarks));
        }
    }


    public delegate void FaviconFetchCompletedEventHandler(object sender, FaviconFetchCompletedEventArgs e);

    public class FaviconFetchCompletedEventArgs : AsyncCompletedEventArgs
    {
        public FaviconFetchCompletedEventArgs(List<RecentBookmark> recentBookmarks)
            : base(null, false, null)
        {
            Result = recentBookmarks;
        }
        public List<RecentBookmark> Result;
    }
}
